const multer = require('multer')
const environment = process.env.NODE_ENV
const stage = require('../config')[environment]

const imageFilter = function (req, file, cb) {
  // accept image only
  if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
    return cb(new Error('Only image files are allowed!'), false);
  }
  cb(null, true)
}

const ebookFilter = function (req, file, cb) {
  // accept image only
  if (!file.originalname.match(/\.(epub|mobi)$/)) {
    return cb(new Error('Only eBook files are allowed!'), false);
  }
  cb(null, true)
}

const uploadBook = multer({
  dest: `${process.env.UPLOAD_PATH}/book`,
  fileFilter: ebookFilter,
  limits: {
    fileSize: stage.fileSize
  }
})

const uploadAvatar = multer({
  dest: `${process.env.UPLOAD_PATH}/user`,
  fileFilter: imageFilter
})


module.exports = {
  uploadAvatar,
  uploadBook
}
